package com.itheima.grow.service.impl;

import com.itheima.grow.service.IThreadCoolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.Executor;

@Service
@Slf4j
public class ThreadCoolServiceImpl implements IThreadCoolService {

    @Resource(name = "asyncServiceExecutor")
    private Executor executor;

    @Autowired
    @Lazy
    private IThreadCoolService iThreadCoolService;


    /**
     * 注意这里 commonal+asyCallBackTest等于asyCallBackTest2
     */
    @Override
    public void commonal() {
        System.out.println("before:"+Thread.currentThread().getName());
        for (int i = 0; i < 100; i++) {
            iThreadCoolService.asyCallBackTest();
        }
    }

    @Async
    public void asyCallBackTest() {
        try {
            //打印当前线程名称
            System.out.println("asyncWay:"+Thread.currentThread().getName());
            //休息1秒这样的话这个线程应该用时100s
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String asyCallBackTest2() {
        //打印当前线程名称
        System.out.println("before:"+Thread.currentThread().getName());
        for (int i = 0; i < 100; i++) {
            executor.execute(()->{
                try {
                    //打印当前线程名称
                    System.out.println(Thread.currentThread().getName());
                    //休息1秒这样的话这个线程应该用时100s
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        return "end";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchCompleteOrder() {
        //方法必须是public的
        return null;
    }
}
